<template>
  <div class="inventory-stock">
    <!-- 页面标题 -->
    <PageHeader 
      title="库存管理" 
      description="管理商品库存，包括入库、出库、调拨等操作"
      icon="Box"
    />
    
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" label-width="80px" inline>
        <el-form-item label="商品名称">
          <el-input v-model="filterForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="filterForm.category" placeholder="请选择分类" clearable>
            <el-option label="电子产品" value="electronics" />
            <el-option label="服装" value="clothing" />
            <el-option label="配件" value="accessories" />
            <el-option label="图书" value="books" />
            <el-option label="软件" value="software" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="充足" value="sufficient" />
            <el-option label="预警" value="warning" />
            <el-option label="缺货" value="outOfStock" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="showStockInDialog">入库</el-button>
      <el-button type="success" @click="showStockOutDialog">出库</el-button>
      <el-button type="warning" @click="showTransferDialog">调拨</el-button>
      <el-button type="info" @click="handleImport">导入库存</el-button>
      <el-button @click="handleExport">导出库存</el-button>
    </div>
    
    <!-- 库存列表 -->
    <el-card class="list-card" shadow="never">
      <el-table :data="inventoryList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="商品ID" width="80" />
        <el-table-column prop="name" label="商品名称" min-width="150" />
        <el-table-column prop="category" label="分类" width="100" />
        <el-table-column prop="sku" label="SKU" width="120" />
        <el-table-column prop="stock" label="库存数量" width="100">
          <template #default="{ row }">
            <span :class="getStockStatusClass(row.stock, row.minStock)">{{ row.stock }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="minStock" label="最低库存" width="100" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="location" label="库位" width="120" />
        <el-table-column prop="lastUpdated" label="最后更新" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" link @click="handleStockIn(row)">入库</el-button>
            <el-button type="warning" link @click="handleStockOut(row)">出库</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 入库对话框 -->
    <el-dialog v-model="stockInDialogVisible" title="商品入库" width="500px">
      <el-form :model="stockInForm" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="stockInForm.productName" disabled />
        </el-form-item>
        <el-form-item label="入库数量" required>
          <el-input-number v-model="stockInForm.quantity" :min="1" />
        </el-form-item>
        <el-form-item label="入库原因">
          <el-select v-model="stockInForm.reason" placeholder="请选择入库原因">
            <el-option label="采购入库" value="purchase" />
            <el-option label="退货入库" value="return" />
            <el-option label="调拨入库" value="transfer" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="stockInForm.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockInDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStockIn">确认入库</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 出库对话框 -->
    <el-dialog v-model="stockOutDialogVisible" title="商品出库" width="500px">
      <el-form :model="stockOutForm" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="stockOutForm.productName" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input v-model="stockOutForm.currentStock" disabled />
        </el-form-item>
        <el-form-item label="出库数量" required>
          <el-input-number v-model="stockOutForm.quantity" :min="1" :max="stockOutForm.currentStock" />
        </el-form-item>
        <el-form-item label="出库原因">
          <el-select v-model="stockOutForm.reason" placeholder="请选择出库原因">
            <el-option label="销售出库" value="sale" />
            <el-option label="调拨出库" value="transfer" />
            <el-option label="损耗出库" value="loss" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="stockOutForm.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockOutDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStockOut">确认出库</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 调拨对话框 -->
    <el-dialog v-model="transferDialogVisible" title="库存调拨" width="500px">
      <el-form :model="transferForm" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="transferForm.productName" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input v-model="transferForm.currentStock" disabled />
        </el-form-item>
        <el-form-item label="调拨数量" required>
          <el-input-number v-model="transferForm.quantity" :min="1" :max="transferForm.currentStock" />
        </el-form-item>
        <el-form-item label="调出库位">
          <el-input v-model="transferForm.fromLocation" disabled />
        </el-form-item>
        <el-form-item label="调入库位" required>
          <el-input v-model="transferForm.toLocation" placeholder="请输入目标库位" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="transferForm.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="transferDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmTransfer">确认调拨</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 导入对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入库存" width="500px">
      <el-form :model="importForm" label-width="100px">
        <el-form-item label="选择文件">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                请上传.xlsx或.csv格式的文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmImport">确认导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from '@vue/runtime-core'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import PageHeader from '@/components/layout/PageHeader.vue'

// 数据模型
interface InventoryItem {
  id: number
  name: string
  category: string
  sku: string
  stock: number
  minStock: number
  unit: string
  location: string
  lastUpdated: string
}

// 筛选表单
const filterForm = reactive({
  name: '',
  category: '',
  status: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 状态
const loading = ref(false)
const inventoryList = ref<InventoryItem[]>([])

// 对话框
const stockInDialogVisible = ref(false)
const stockOutDialogVisible = ref(false)
const transferDialogVisible = ref(false)
const importDialogVisible = ref(false)

// 表单数据
const stockInForm = reactive({
  productId: 0,
  productName: '',
  quantity: 1,
  reason: '',
  remark: ''
})

const stockOutForm = reactive({
  productId: 0,
  productName: '',
  currentStock: 0,
  quantity: 1,
  reason: '',
  remark: ''
})

const transferForm = reactive({
  productId: 0,
  productName: '',
  currentStock: 0,
  quantity: 1,
  fromLocation: '',
  toLocation: '',
  remark: ''
})

const importForm = reactive({
  file: null as File | null
})

// 获取库存状态类名
const getStockStatusClass = (stock: number, minStock: number) => {
  if (stock <= 0) return 'stock-out'
  if (stock <= minStock) return 'stock-warning'
  return 'stock-sufficient'
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', filterForm)
  loadInventoryList()
}

// 重置
const handleReset = () => {
  filterForm.name = ''
  filterForm.category = ''
  filterForm.status = ''
  loadInventoryList()
}

// 加载库存列表
const loadInventoryList = () => {
  loading.value = true
  // 模拟数据
  setTimeout(() => {
    inventoryList.value = [
      {
        id: 1,
        name: 'iPhone 15 Pro',
        category: '电子产品',
        sku: 'IP15P-256G',
        stock: 50,
        minStock: 20,
        unit: '台',
        location: 'A区-01',
        lastUpdated: '2025-11-15 14:30:25'
      },
      {
        id: 2,
        name: 'MacBook Pro 14"',
        category: '电子产品',
        sku: 'MBP14-M2-512G',
        stock: 15,
        minStock: 10,
        unit: '台',
        location: 'A区-02',
        lastUpdated: '2025-11-15 10:15:42'
      },
      {
        id: 3,
        name: 'AirPods Pro',
        category: '电子产品',
        sku: 'APRO2-白色',
        stock: 0,
        minStock: 30,
        unit: '副',
        location: 'A区-03',
        lastUpdated: '2025-11-14 16:22:18'
      },
      {
        id: 4,
        name: '男士商务衬衫',
        category: '服装',
        sku: 'MS-42-WHITE',
        stock: 8,
        minStock: 20,
        unit: '件',
        location: 'B区-01',
        lastUpdated: '2025-11-15 09:45:33'
      },
      {
        id: 5,
        name: '无线充电器',
        category: '配件',
        sku: 'WC-15W-QI',
        stock: 120,
        minStock: 50,
        unit: '个',
        location: 'C区-01',
        lastUpdated: '2025-11-14 11:20:15'
      }
    ]
    pagination.total = 50
    loading.value = false
  }, 500)
}

// 显示入库对话框
const showStockInDialog = () => {
  // 设置默认值
  stockInForm.productId = 0
  stockInForm.productName = ''
  stockInForm.quantity = 1
  stockInForm.reason = ''
  stockInForm.remark = ''
  stockInDialogVisible.value = true
}

// 显示出库对话框
const showStockOutDialog = () => {
  // 设置默认值
  stockOutForm.productId = 0
  stockOutForm.productName = ''
  stockOutForm.currentStock = 0
  stockOutForm.quantity = 1
  stockOutForm.reason = ''
  stockOutForm.remark = ''
  stockOutDialogVisible.value = true
}

// 显示调拨对话框
const showTransferDialog = () => {
  // 设置默认值
  transferForm.productId = 0
  transferForm.productName = ''
  transferForm.currentStock = 0
  transferForm.quantity = 1
  transferForm.fromLocation = ''
  transferForm.toLocation = ''
  transferForm.remark = ''
  transferDialogVisible.value = true
}

// 导入库存
const handleImport = () => {
  importDialogVisible.value = true
}

// 导出库存
const handleExport = () => {
  ElMessage.success('库存导出功能已触发')
  // 实际项目中应该调用导出API
  console.log('导出库存')
}

// 处理文件上传
const handleFileChange = (file: any) => {
  importForm.file = file.raw
}

// 确认导入
const confirmImport = () => {
  if (!importForm.file) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }
  
  ElMessage.success('库存导入成功')
  importDialogVisible.value = false
  loadInventoryList()
}

// 编辑库存
const handleEdit = (row: InventoryItem) => {
  ElMessage.info(`编辑商品: ${row.name}`)
  console.log('编辑库存:', row)
}

// 入库操作
const handleStockIn = (row: InventoryItem) => {
  stockInForm.productId = row.id
  stockInForm.productName = row.name
  stockInForm.quantity = 1
  stockInForm.reason = ''
  stockInForm.remark = ''
  stockInDialogVisible.value = true
}

// 出库操作
const handleStockOut = (row: InventoryItem) => {
  stockOutForm.productId = row.id
  stockOutForm.productName = row.name
  stockOutForm.currentStock = row.stock
  stockOutForm.quantity = 1
  stockOutForm.reason = ''
  stockOutForm.remark = ''
  stockOutDialogVisible.value = true
}

// 删除库存
const handleDelete = (row: InventoryItem) => {
  ElMessageBox.confirm(
    `确定要删除商品 "${row.name}" 吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    ElMessage.success('删除成功')
    loadInventoryList()
  }).catch(() => {
    // 用户取消删除
  })
}

// 确认入库
const confirmStockIn = () => {
  if (stockInForm.quantity <= 0) {
    ElMessage.warning('入库数量必须大于0')
    return
  }
  
  if (!stockInForm.reason) {
    ElMessage.warning('请选择入库原因')
    return
  }
  
  console.log('确认入库:', stockInForm)
  ElMessage.success('商品入库成功')
  stockInDialogVisible.value = false
  loadInventoryList()
}

// 确认出库
const confirmStockOut = () => {
  if (stockOutForm.quantity <= 0) {
    ElMessage.warning('出库数量必须大于0')
    return
  }
  
  if (stockOutForm.quantity > stockOutForm.currentStock) {
    ElMessage.warning('出库数量不能大于当前库存')
    return
  }
  
  if (!stockOutForm.reason) {
    ElMessage.warning('请选择出库原因')
    return
  }
  
  console.log('确认出库:', stockOutForm)
  ElMessage.success('商品出库成功')
  stockOutDialogVisible.value = false
  loadInventoryList()
}

// 确认调拨
const confirmTransfer = () => {
  if (transferForm.quantity <= 0) {
    ElMessage.warning('调拨数量必须大于0')
    return
  }
  
  if (transferForm.quantity > transferForm.currentStock) {
    ElMessage.warning('调拨数量不能大于当前库存')
    return
  }
  
  if (!transferForm.toLocation) {
    ElMessage.warning('请输入目标库位')
    return
  }
  
  if (transferForm.fromLocation === transferForm.toLocation) {
    ElMessage.warning('调出库位和调入库位不能相同')
    return
  }
  
  console.log('确认调拨:', transferForm)
  ElMessage.success('库存调拨成功')
  transferDialogVisible.value = false
  loadInventoryList()
}

// 分页操作
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadInventoryList()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadInventoryList()
}

// 生命周期
onMounted(() => {
  loadInventoryList()
})
</script>

<style scoped>
.inventory-stock {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.action-buttons .el-button {
  margin-right: 10px;
}

.list-card {
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.stock-out {
  color: #f5222d;
  font-weight: bold;
}

.stock-warning {
  color: #faad14;
  font-weight: bold;
}

.stock-sufficient {
  color: #52c41a;
}
</style>